//宁海水库

import {
	ElMessage
} from "element-plus";


function hMsg(msg) {

	ElMessage(msg);
}

function hMsgWarn(msg) {
	ElMessage({
		message: msg,
		type: 'warning',
	});
	console.log("数据返回警告", msg);
}

function hMsgError(msg) {
	ElMessage.error(msg);

}
/**
 * 递归无级树
 * @param {Array} data  
 * @param {Object} parent 顶层父级
 * @param {String} pk 主键名
 * @param {String} ck 子键名
 * @param {String} child 子项名
 */
function hTree(data, parent, pk, ck, child) {

	if (data.length == 0) {
		return;
	}
	pk = pk || "key",
		ck = ck || "key_self",
		child = child || "children";
	//root parent
	var root = data.filter(t => t[ck] == null || t[ck].length == 0);
	if (root.length > 0) {
		for (var i = 0; i < root.length; i++) {
			var ritem = root[i];
			var ix = data.findIndex(t => t[pk] == ritem[pk]);
			data.splice(ix, 1);
		}
		for (var i = 0; i < root.length; i++) {
			var ritem = root[i];
			ritem[child] = [];
			ritem.ilast = ritem.ilast || null;
			hTree(data, ritem, pk, ck, child);
			parent[child].push(ritem);
			//i--;
		}
		return;
	}

	//children
	var children = data.filter(t => t[ck] == parent[pk]);
	if (children.length > 0) {

		for (var i = 0; i < children.length; i++) {
			var ritem = children[i];
			var ix = data.findIndex(t => t[pk] == ritem[pk]);
			data.splice(ix, 1);
		}
		for (var i = 0; i < children.length; i++) {
			var ritem = children[i];
			ritem[child] = [];
			ritem.ilast = ritem.ilast;

			hTree(data, ritem, pk, ck, child);
			parent[child].push(ritem);
			//i--;
		};

	}

}

export class NingHai {
	_v1;
	///asdf
	_v1Root; //: String三方根接口
	_v1Disp; //广播资源
	_v1Resource; //
	_host; //: 数据主机
	_root; //: 公共接口
	_tk; //后台验证
	_tm;

	//第三方的验证
	a3tk = '{"X-GXToken":"8186d5f3-3914-7159-689b-655e6e047355"}';

	//接口访问用户名
	userNameNH = "Builtin_slj";
	userSys = 'system';
	userAdmin = 'admin';
	_table = {

		/**图元区域数据  
		 *{ ID,Json,Other,CreateDate }
		 */
		area: 'T_AreaDat',

		/**图元点数据
		 * {ID,AreaId,DatType,Json,Other,CrateDate,ProjGid}
		 */
		mark: 'T_GardenDat',

		/**点类型
		 * {ID,Name,Other,CrateDate}
		 */
		markType: 'T_GardenType',

		/**图元巡检路径，水位检测点
		 * {ID,Name,Json,Other,CreateDate}
		 */
		path: 'T_PatrolLine',

		/**监控预案->新类型 文本播报预案
		 * {ID,GIds 图元点列表,Name,Other,CreateDate}
		 */
		plan: 'T_Preplan',

		/**漂流面，裁剪面
		 * {ID,Json,Remark}
		 */
		river: 'T_River',

		/**投影区域
		 *  {`ID`,`Gid`,`Json`,`Remark`,`CreateDate``t_cam_projection`}
		 */
		projection: 'T_Cam_Projection',

		/**点分类
		 * 
		 */
		labelType: "T_Label",

		/**报警配置信息
		 * 
		 */
		cfgAi: "T_cfg_ai",
	};

	constructor({
		host
	}) {
		this._host = host;
		this._root = `${host}/api/Public`;
		this._v1Root = window.audioHost;
		let v1 = `${window.audioHost}/api/v1`;

		let bordcast = `${v1}/dispatch`;
		let resource = `${v1}/resource`;
		this._v1 = v1;
		this._v1Disp = bordcast;
		this._v1Resource = resource;
	}


	/**tk 检查
	 * 
	 */
	hCheckTk() {
		let str = localStorage.getItem('token');
		//console.log("token", str);
		let role;
		try {
			role = JSON.parse(str);
			this.tm = role.tm;
			this._tk = role.user.token;
		} catch (e) {
			//TODO handle the exception
		}
		return this._tk;
	}

	/**
	 * @param {Object} d
	 * @param {Object} b
	 * @param {Object} cmd
	 * @param {Object} fullcmd
	 */
	hDoPost(d, b, cmd, fullcmd) {
		let din;
		let path = cmd ? `${this._root}/${cmd}` : d.urlstr;
		// if (fullcmd) {
		// 	path = `${this._host}/${fullcmd}`;
		// }
		if (d) {
			din = d.data;
		}
		//		console.log("hDoPost", path, d, this._tk);
		this.hCheckTk();
		let tk = this._tk;
		$.ajax({
			type: "POST",
			url: path,
			contentType: "application/json",
			cache: false,
			dataType: "JSON",
			data: din,
			headers: {
				Authorization: tk
			},
			success: function (e) {
				if (e.code != 200) {
					console.error("数据返回", path, e);
					if (e.code == 3) {
						b?.(e.result);
						return;
					}
					ElMessage.error("数据异常" + path);
					b?.(false);
					return;
				}
				let dr;
				try {
					if (e.data && typeof (e.data) != 'object') {
						dr = e.data;
					} else {
						dr = data;
					}
				} catch (e) {
					dr = e;
					//TODO handle the exception
				}
				b?.(dr);
			},
			error: function (e) {
				//ElMessage.error("数据请求错误" + path);
				b?.(false, e.statusText);
				console.warn("数据请求错误", path, din, e);
			}
		});

	}

	/**添加/更新数据
	 * @param {Object} dat 数据
	 * @param {Object} tb 对象
	 * @param {Object} b 返回
	 */
	hAddPost(dat, tb, b) {
		if (dat.id) {
			dat.id = dat.id * 1;
		} else if (dat.ID) {
			dat.ID = dat.ID * 1;
		} else {
			dat.ID = 0;
		}
		let d = this.hAddPram(tb, dat);
		this.hDoPost(d, b, "SvaeDat");
	}

	/**获取数据
	 * @param {Object} d
	 * @param {Object} b 
	 */
	hGetDat(d, b) {
		this.hDoPost(d, b, 'QueryDat');
	}

	/**删除数据
	 * @param {Object} id
	 * @param {Object} tb
	 * @param {Object} b
	 */
	hDelPost(id, tb, b) {
		let d = this.hDel(tb, id);
		this.hDoPost(d, r => {
			console.log("删除返回", r);
			b?.(r);
		}, "DelDat");
	}

	/**获取第三方接口数据
	 * @param {Object} d
	 * @param {Object} b 
	 */
	hGetDatApi3(d, b) {
		// this.hDoPost(d, b, 'GetTPDat');
		this.hDoPost(d, b);
	}

	/**报警信息
	 * @param {Object} b
	 */
	hGetAiMsg(b) {
		this.hDoPost(null, b, 'GetSetDat');
	}
	/**
	 * @param {String} u 路径
	 * @param {Object} d 参数
	 * @param {String} m 三方的访问方式
	 */
	parmApi(u, d, m) {
		return {
			urlstr: u,
			method: m || 'post',
			headers: this.a3tk,
			data: JSON.stringify(d),
		}
	};

	//获取数据
	hGet(tb) {
		return {
			"tableName": tb,
			"field": "*",
			"where": ""
		}
	};

	//保存新数据
	hAddPram(tb, dat) {
		let id = 0;
		if (!isNaN(dat.id) || !isNaN(dat.ID)) {
			id = Number(dat.id) || Number(dat.ID);
		}
		return {
			"id": id,
			"tableName": tb,
			"data": JSON.stringify(dat),
		}
	};

	//删除数据
	hDel(tb, id) {
		return {
			"id": id * 1,
			"tableName": tb
		}
	};


	hDoGet(d, b) {
		//console.log("getdat", d, b);
		this.hGetDat(d, b);
	}


	/**登录
	 * @param {Object} u
	 * @param {Object} b
	 */
	hLogin(u, b) {
		this.hDoPost(u, (r, m) => {

			let tk = r.token;
			if (!r || !tk) {
				b?.(false, r || m);
				return;
			}

			this._tk = tk;
			r.user.token = tk;
			console.log("tk", r.token);
			b?.(r.user);
		}, null, `Login/GetToken`)
	}
	hGetUser(b) {
		let d = this.hGet("t_user");
		this.hDoGet(d, b);
	}
	hAddUser(u, b) {
		u.id = 0;
		this.hAddPost(u, "t_user", (r) => {
			b?.(r);
		},);
	}
	hDelUser(id, b) {
		this.hDelPost(id, "t_user", b);
	}
	hResetPwd(dat, b) {
		this.hAddPost(dat, 't_user', (t) => {
			console.log("密码已更新", t);
			let r = eval(t);
			b?.(r);
		});
	}

	/**添加/更新标签类型
	 * @param {Object} dat d.ID不等于0时为更新
	 * @param {Object} b
	 */
	hAddLabelType(dat, b) {
		this.hAddPost({
			ID: dat.ID,
			key: dat.key,
			key_self: dat.key_self,
			label: dat.label,
			ilast: dat.ilast,
			iprev: dat.iprev
		}, this._table.labelType, b);
	}
	/**删除标签类型
	 * @param {Object} dat
	 * @param {Object} b
	 */
	hDelLabelType(dat, b) {
		let cs = dat.children;
		this.hDelPost(dat.ID, this._table.labelType, b);

		for (var i = 0; i < cs.length; i++) {
			this.hDelLabelType(cs[i], b);
		}

	}
	/**获取标签类型
	 * @param {Object} parent
	 */
	hGetLabelType(parent) {
		let d = this.hGet(this._table.labelType);
		this.hDoGet(d, (r) => {
			var dats = r;
			hTree(dats, parent, 'key', 'key_self', 'children');
		});
	}


	/**点，标注
	 * @param {Object} json
	 */
	hAddPoint(json) {
		let d = this.hAddPram(this._table.mark, json);
		this.hDoPost(d);
	};
	hDelPoint(json) {

	}

	/**区域
	 * @param {Object} json
	 */
	hAddArea(json, b) {
		let datId = json.properties.datId;
		let d = this.hAddPram(this._table.area, {
			'ID': datId || 0,
			'Json': JSON.stringify(json),
			'Other': json.properties.camName,
			'CreateDate': new Date()
		});

		console.log("api 保存区域", d);
		this.hDoPost(d, b);
	};
	hGetArea(b) {
		let d = this.hGet(this._table.area);
		this.hDoGet(d, b);
	}

	/**河流
	 * @param {Object} json
	 */
	hAddRiver(json, clip, isls, b) {
		console.log("河流保存", json);
		this.hAddPost({
			'ID': 0,
			'Json': JSON.stringify(json),
			'GId': isls || 0, //流水
			'Remark': clip || 0 //裁剪面
		}, this._table.river, (t) => {
			console.log("河流保存返回:", t);
			if (typeof (t) == "object") {
				b?.(t);
			} else {
				let dts = eval(t);
				b?.(dat);
			}
		});
	}
	hDelRiver(id, b) {

		console.log("删除", id);
		this.hDelPost(id, this._table.river, b);

		//let d = this.hDel(this._table.river, id);
		//this.hDoGet(d);
	};

	hGetRiver(b) {
		let d = this.hGet(this._table.river);
		this.hDoGet(d, b);
	}

	/**添加点
	 * @param {Object} json
	 */
	hAddMarke(json, pgid, b) {
		let gid = json.properties.Gid;
		let d = this.hAddPram(this._table.mark, {
			'ID': gid || 0,
			'AreaId': -1,
			'DatType': json.properties.DatType,
			'Json': JSON.stringify(json),
			'Other': json.properties.Other || 0,
			'ProjGid': pgid || '',
			'CrateDate': new Date()
		});
		//ID, AreaId, DatType, Json, Other, CrateDate
		//console.log(json);
		this.hDoPost(d, (t) => {
			let dts = eval(t);
			if (dts.find) {
				let dat = dts.find(v => v.GId == gid);

				b?.(dat);
			}
		});
	}

	hDelMarke(id) {
		let d = this.hDel(this._table.mark, id);
		this.hDoGet(d);
		console.log("删除", d);
	}



	/**水位检测点
	 * @param {Object} json
	 * @param {Object} b
	 */
	hAddSwjc(json, b) {
		let gid = json.properties.Gid;
		let d = this.hAddPram(this._table.path, {
			'ID': gid || 0,
			'Name': json.properties.name,
			'Json': JSON.stringify(json),
			'Other': json.properties.Other
		});

		//{ID,Name,Json,Other,CreateDate}		
		console.log("水位检测点", d, json);
		this.hDoPost(d, (t) => {
			console.log("水位检测点保存完成", t);
			let dts = eval(t);
			if (dts.find) {
				let dat = dts.find(v => v.GId == gid);
				b?.(dat);
			}
		}, "SvaeDat");
	}
	hCfgSwjc(d, b) {

		this.hDoPost(d, (t) => {
			console.log("水位检测点配置保存完成", t);
			b?.(t);
		}, 'UpdataSw');
	}
	hGetSwjc(b) {
		console.log("查询水位信息", b);
		let d = this.hGet(this._table.path);
		this.hDoGet(d, r => {
			console.log("水位信息", r);
			b?.(r);
		});
	}



	/**报警响应配置
	 * @param {Object} dat
	 * @param {Object} b
	 */
	hAddCfg(dat, b) {
		this.hAddPost(dat, this._table.cfgAi, (t) => {
			let dts = eval(t);
			b?.(dat);
		});

	}
	hGetCfgs(b) {
		let d = this.hGet(this._table.cfgAi);
		this.hGetDat(d, b);
	}




	/**播报预案
	 * @param {Object} dat
	 * @param {Object} b
	 */
	hAddAY(dat, b) {
		this.hAddPost({
			'ID': dat.id || 0,
			'Name': dat.label,
			'Other': dat.value,
			'GId': '0',
			'CreateDate': new Date()
		}, this._table.plan, (r) => {
			b?.(r);
		},);
	}

	hGetAY(b) {
		let d = this.hGet(this._table.plan);
		this.hDoGet(d, r => {
			let dts = r?.map?.(t => {
				return {
					label: t.Name,
					id: t.ID,
					value: t.Other
				}
			})
			b?.(dts);
		});
	}


	/**
	 * @param {Object} id
	 * @param {Object} b callback  id
	 */
	hDelAY(id, b) {
		this.hDelPost(id, this._table.plan, b);
	}

	hGetMarks(b) {
		let d = this.hGet(this._table.mark);
		this.hDoGet(d, b);
	}
	hAddProjection(json) {
		json.properties.style = {};
		//console.log(json);
		// {`ID`,`Gid`,`Json`,`Remark`,`CreateDate``t_cam_projection`}
		let d = this.hAddPram(this._table.projection, {
			'ID': 0,
			'Gid': json.properties.id,
			'Json': JSON.stringify(json),
			'Remark': '',
			'CrateDate': new Date()
		});
		this.hDoPost(d);
	}
	hGetProjectionById(gid, b) {
		let d = this.hGet(`${this._table.projection} where Gid='${gid}'`);
		console.log("查询", d, JSON.stringify(d));
		this.hDoGet(d, b);
	}
	hDelhDelProjn(id) {
		let d = this.hDel(this._table.projection, id);
		this.hDoGet(d);
		console.log("删除", d);
	}
	/**巡检路径
	 * @param {Object} json
	 */
	hAddPath(json) {

		let d = this.hAdd(this._table.path, json);
		this.hDoPost(d);
	}
	/**数据类型，监控，广播
	 * 
	 */
	hGetDatType() {
		let d = this.hGet(this._table.markType);
		this.hDoGet(d);
	}

	hGdian(cmd, d, b) {
		let dat = this.parmApi(cmd, d);

		//console.log("数据请求", dat, b);
		this.hGetDatApi3(dat, (t) => {
			let r = null;
			try {
				if (typeof (t) == "object") {
					r = t;
				} else {
					r = JSON.parse(t); //eval('(' + t + ')'); //
				};
				b?.(r.result || r);
			} catch (e) {
				console.error("异常转换：", t, e);
				b?.(t);
			}
		});
	}
	hGdianV1(d, b, cmd) {
		let url = this._v1;
		if (cmd) {
			url += '/' + cmd;
		}
		//	console.log("数据请求dispatch", d,cmd,b);
		this.hGdian(url, d, b);
	}
	hGdianDispatch(d, b, cmd) {
		let url = this._v1Disp;
		if (cmd) {
			url += '/' + cmd;
		}
		//	console.log("数据请求dispatch", d,cmd,b);
		this.hGdian(url, d, b);
	}
	hGdianResource(d, b, cmd) {
		let url = this._v1Resource;
		if (cmd) {
			url += '/' + cmd;
		}
		//	console.log("数据请求resource", d,cmd,b); 
		this.hGdian(url, d, b);
	}



	/**请求广播数据
	 * @param {Object} b
	 */
	hServerBroadcast(b, dat) {
		let ebrId = "",
			areaId = 1;
		if (dat) {
			if (dat.ebrId) {
				ebrId = dat.ebrId;
			}
			if (dat.areaId) {
				areaId = dat.areaId;
			}
		}

		this.hGdianResource({
			"jsonrpc": "2.0",
			"method": "queryTerminals",
			"id": 17759, // 请求序号ID，可以采用递增值或随机值，主要用于区分不同的请求，服务器回复包中的ID会与请求的ID一致
			"params": {
				"userName": this.userNameNH, // "admin",
				"combined": {
					"name": "", // 指定以终端名称为条件进行查询，支持模糊查询 ""为通配
					"phy": "", // 指定以终端物理编码为条件进行查询，支持模糊查询 ""为通配
					"ebrId": ebrId, // 指定以终端资源编码为条件进行查询 ""为通配
					"online": -1, // 指定以终端在线状态为条件进行查询 -1：全部状态 0-未知状态 1-在线状态 2-离线状态
					"work": -1, // 指定以终端工作状态为条件进行查询 -1：全部状态 1-空闲状态 2-播放中 3-故障
					"heartDuration": 0, // 默认填0
					"deviceType": -1, // 指定设备类型为条件进行查询 -1：全部类型设备 1-户外收扩机 2-户外音柱 3-室内音箱
					"day": 0, // 默认填0
					"hour": 0, // 默认填0
					"mi": 0, // 默认填0
					"second": 0, // 默认填0
					"ip": "", // 指定设备IP地址为条件进等地查询 ""为通配
					"level": 0, // 指定设备区域等级为条件进行查询 默认为0
					"softversion": "", // 指定设备软件版本为条件进行查询 ""为通配
					"swSame": true, // true-只查看版本与softversion一致的终端 false-只查看版本与softversion不一致的终端
					"areaId": areaId, // 区域ID, 1代表查询所有区域分组下的终端
					"filter": true, // 是否只给出用户权限范围内的终端，默认true
					"regex": true, // 是否启用模糊匹配
					"limit": 100, // 分页查询，单页大小，大于0
					"offset": 0 // 偏移的终端个数，不是页数
				}
			}
		}, b);

		return;

	};
	/**请求区域数据
	 * @param {Object} b
	 */
	hServerAreaInfo(b) {
		this.hGdianResource({
			"jsonrpc": "2.0",
			"method": "queryUserPermissionAreaWithStatus",
			"id": 18637,
			"params": {
				"destUserName": this.userNameNH, // "system",
				"filter": false,
				"areaId": 1,
				"userName": this.userNameNH // "system"
			}
		}, b);
	};

	/**任务播出评估
	 * @param {Object} b
	 */
	hServerBroadcastDispatch(b) {
		let d = {
			"jsonrpc": "2.0",
			"method": "queryAdapterTaskInfo",
			"id": 11752,
			"params": {
				"ebmId": "43302260000000314010201202304200125" //指定任务
			}
		};
		this.hGdianDispatch(d, b);

		/**返回数据
		 * {
	"id":41502,
	"jsonrpc":"2.0",
	"result":{//播出结果统计	
			"deviceCount":100,//预计覆盖的设备总数(所有带回传和不带回传的设备)
			"rebackDeviceCount":100,//预计传覆盖的且是具有带回传功能的设备总数 
			"workTotal":80,//实际响应的设备总数
			"totalRate":"0.8",//响应率 范围0.00 - 1 以 workTotal/deviceCount       得出的结果
			"rebackRate":"0.8",//响应率 范围0.00 - 1 以 workTotal/rebackDeviceCount得出的结果
			"devices":[{//这部分可以用来在地图上展示
					"name":"设备名称"， 
					"gps"：{		经纬度
						"lat":"",
						"lng":"",},
					"reback":0,//0:不带回传 1：带回传
					"work":1,// 1：当前设备响应了 0：当前设备未响应
				}]}} */
	}


	/**广播日志
	 * @param {Object} b
	 */
	hServerBroadcastLog(b) {

		let d = {
			"jsonrpc": "2.0",
			"method": "queryAdapterTaskLogs",
			"id": 11752,
			"params": {
				"limit": 100,
				"offset": 0,
				"taskLogCondition": {
					"title": "", //标题过滤， 空字符串:不做过滤条件  ，有数据，按标题过滤任务
					"taskState": -1, //任务状态 -1：不做过滤条件  0：未处理 1：等待播发 2：播发中 3：播发成功 4：播发失败 5：播发取消
					"bcastBy": "", //创建者过滤， 空字符串:不做过滤条件  ，有数据，按标任务创建者过滤任务
					"sourceTypes": [

					],
					"level": -1, //播出级别 -1：不做过滤条件  1：1级（特别重大）2：2级（重大）3：3级（较大）4：4级（一般）	 
					"class": -1, //播出类型 -1：不做过滤条件  1.发布系统演练 2.模拟演练  3。实际演练  4：应急广播 5:日常广播
					"startTime": "",
					"endTime": "",
					"abnormal": 0, //固定这样填写
					"ebmId": "", //固定这样填写
					"dateRange": [ //固定这样填写
						"",
						""
					]
				},
				"userName": this.userNameNH
			}
		};
		this.hGdianDispatch(d, b);
		return;
		//
	}

	/**播出统计
	 * @param {Object} b 
	 */
	hServerBroadcastTask(b) {
		let d = {
			"jsonrpc": "2.0",
			"id": 0,
			"method": "taskStatistics",
			"params": {
				"userName": this.userNameNH
			}
		};
		this.hGdianDispatch(d, b);
		/**播出统计 返回数据 
		 * {
	"id":0,
	"jsonrpc":"2.0",
	"result":{
		"daily":{ //日常任务
			"day30Level1Count":26, //30天内 播出级别是1的任务个数
			"day30Level2Count":11,//30天内 播出级别是2的任务个数
			"day30Level3Count":18,//30天内 播出级别是3的任务个数
			"day30Level4Count":47,//30天内 播出级别是4的任务个数
			"day30TaskCount":102,//30天内 播出任务总个数
			"day3Level1Count":5,//3天内 播出级别是1的任务个数
			"day3Level2Count":11,//3天内 播出级别是2的任务个数
			"day3Level3Count":0,//3天内 播出级别是3的任务个数
			"day3Level4Count":1,//3天内 播出级别是4的任务个数
			"day3TaskCount":17,//3天内 播出任务总个数
			"day7Level1Count":9,//3天内 播出级别是1的任务个数
			"day7Level2Count":11,//7天内 播出级别是2的任务个数
			"day7Level3Count":0,//7天内 播出级别是23的任务个数
			"day7Level4Count":3,//7天内 播出级别是4的任务个数
			"day7TaskCount":23//7天内 播出任务总个数
		},
		"ebm":{//应急任务
			"day30Level1Count":0,
			"day30Level2Count":0,
			"day30Level3Count":0,
			"day30Level4Count":1,
			"day30TaskCount":1,
			"day3Level1Count":0,
			"day3Level2Count":0,
			"day3Level3Count":0,
			"day3Level4Count":0,
			"day3TaskCount":0,
			"day7Level1Count":0,
			"day7Level2Count":0,
			"day7Level3Count":0,
			"day7Level4Count":0,
			"day7TaskCount":0
		}   }} */
	}


	/**广播资源统计
	 * @param {Object} b 
	 */
	hServerBroadcastResource(b) {

		let d = {
			"jsonrpc": "2.0",
			"id": 0,
			"method": "queryUserPermissionAreaWithStatus",
			"params": {
				"destUserName": this.userNameNH, //"system", //目标用户--这里可以和 "userName" 节点一直，查询自己的
				"areaId": 4030, //区域ID
				"filter": true, //--固定填写死
				"userName": this.userNameNH, //"system" //当前用户
			}
		};
		this.hGdianResource(d, b);
		/**
		 * 返回数据 
		 */
		return;

	};

	/**广播的关联监控
	 * @param {Object} b
	 * @param {Object} broadcast 
	 * @param {Object} u
	 */
	hServerBroadcastCam(broadcast, b) {
		let d = {
			"jsonrpc": "2.0",
			"method": "queryTerminalRefCamInfo",
			"id": 65155,
			"params": {
				"userName": this.userNameNH, //"shadow",
				"terminalIds": [broadcast.id] //二选一
				//"areaId": 1 //二选一
			}
		};
		this.hAjax(d, b, 'vab');
		/**
		 * 返回数据 
		 * {
			"id": 65155,
			"jsonrpc": "2.0",
			"result": {
				"cameras": [
					{
						"at": "2023-04-21 15:04:15",//创建时间
						"by": "admin",
						"gFull": "根目录|宁海水利|低位监控|228国道16号在黄土岭33号杆", //所属于分组节点（全部展示）
						"gId": 28,
						"gName": "228国道16号在黄土岭33号杆",//所属于直属的分组节点
						"gps": {
							"lat": "29.275635",
							"lng": "121.428641"//摄像头经纬度
						},
						"heartTime": "2023-04-21 16:46:14", //心跳时间
						"id": 28,
						"name": "228国道16号在黄土岭33号杆可见光",
						"state": 1	//0:未知 1在线 2在线-故障 3离线
						"identifierId": "0108d888d99545eca7d3bb9c456e22e1", //海康cameralndexCode
						"syncFlag":2,//0：手动添加 2：同步自海康ISC安防平台
					}
				]
			}
		}
		 */
	}

	//实时喊话
	hServerBroadcastLiveTask(params, b) {
		let d = {
			"jsonrpc": "2.0",
			"method": "startLiveTask",
			"id": 39690,
			"params": {
				...params
			}
		};
		//console.log("请求实时喊话", d);
		this.hGdianDispatch(d, b);
		/**
		 * 返回数据 
		 */
	};

	/**维持/停止喊话任务
	 * @param {Object} b
	 * @param {Object} params
	 */
	hServerBroadcastLiveTaskKeep(params, b) {

		let d = {
			"jsonrpc": "2.0",
			"method": "keepLiveTask",
			"id": 20779,
			"params": {
				...params,
				// keepTime: 0, //0停止任务，>0 需要维持的时间
				// ebmId: '44400000....', //需要维持的任务编号
				userName: 'admin' //this.userNameNH //
			}
		};
		this.hGdianDispatch(d, b);
		/**
		 * 返回数据 
		 */
	};

	/**文本喊话
	 * @param {Object} b
	 */
	hServerBroadcastLiveTaskText(dat, b) {

		let s = 5;
		let tms = 1;
		let dua = 0;
		let ed = new Date();
		ed.setSeconds(new Date().getSeconds() + s + 3);
		if (dat.mm) {
			//播放时间 分钟
			ed.setMinutes(new Date().getMinutes() + dat.mm);
			dua = 0;
		} else if (dat.tms) {
			//次数播放
			tms = dat.tms;
			dua = 2;
			//播放间隔
			//dat.iitv 
		}
		let d = {
			"jsonrpc": "2.0",
			"method": "createCronTask",
			"id": 0,
			"params": {
				"ebmClass": 5, // 日常广播 - 5 应急广播-4
				"severity": 4, // 事件等级 1~4,1等级最高
				"volume": dat.v, // 0-静音 1~100 255-跟随终端存储的音量
				"duration": dua, // 播出的模式 0: 按照 开播时间到 结束时间来播放 1:按照每天时间段来播放， 2:按照次数播放
				"playTimes": tms, // 播放次数
				"diffTime": s, // 播出指令延迟于内容多少秒发送，保证广播内容能完整的播放完
				"workdays": [1, 2, 3, 4, 5, 6, 0],
				"languageCode": "zho",
				"title": dat.title || "未命名标题_",
				"content": dat.text, // 播出的文本内容
				"correctStartTime": 1, // 1-根据后台任务创建时间即时进行播放
				"startTime": new Date().format("yyyy-MM-dd HH:mm:ss"),
				"endTime": ed.format("yyyy-MM-dd HH:mm:ss"),
				"eventType": "00000",
				"useAreaGroup": 0,
				"areaCodes": [],
				"phys": dat.ids, //[...dat.ids], //"63310020010060314010402"设备的物理码或资源编码
				"areaGroups": [],
				"audios": [],
				"inputId": 0,
				"outputIds": [2],
				"createdBy": "admin"
			}
		};
		console.log("文本播出", d, "预案", dat);
		this.hGdianV1(d, r => {
			console.log("文本播出", d, "返回", dat);
			b?.(r);
		}, 'hornAdapterCronTask');
		/**
		 * 返回数据 
		 */
	}

	/**停止文本喊话
	 * @param {Object} ids
	 * @param {Object} b
	 */
	hServerBroadcastLiveTaskTextStop(ids, b) {

		for (var i = 0; i < ids.length; i++) {
			let id = ids[i];
			let dat = {
				"jsonrpc": "2.0",
				"method": "stopTask",
				"id": 0,
				"params": {
					"ebmId": id
				}
			}
			this.hGdianV1(d, r => {
				//console.log("文本播出", d, "返回", dat);
				b?.(r);
			}, 'hornAdapterCore');
		}
	}


	/**任务评估
	 * @param {Object} b
	 */
	hServerBroadcastTaskBcast(ebmId, b) {

		let d = {
			"jsonrpc": "2.0",
			"method": "queryTaskBcastEvaluate",
			"id": 65155,
			"params": {
				"ebmId": ebmId
			}
		}
		//console.log("任务评估",d);
		this.hGdianDispatch(d, b);
		return;
	}


	hServer2(rt, d, b) {
		let p = this._v1Root + "/water/" + rt;
		let dat = this._hAjax(p, d);
		this.hDoPost(dat, (t) => {
			//console.log("水位信息查询：", t, d);
			let r = null;
			try {
				if (typeof (t) === typeof ({})) {
					r = t;
				} else {
					r = JSON.parse(t); //eval('(' + t + ')'); //
				};
				b?.(r.result || r);
			} catch (e) {
				console.error("异常转换：", t, e);
			}
		});
	}

	/**水位信息 查询测站列表信息
	 * @param {Object} b
	 */
	hServerWater(b) {
		let d = {
			"jsonrpc": "2.0",
			"method": "stations",
			"id": 0,
			"params": {
				"page": {
					"current": 1, //当前第几页
					"size": 200 //每页显示条数
				}
			}
		}
		this.hServer2('station', d, r => {
			b?.(r.data.records);
			return;
		});
		return;

	}
	/**水位信息 查询测站实时水位信息
	 * @param {Object} stcd 测站编号
	 */
	hServerWaterInfo(stcd, b) {
		if (!stcd) {
			console.warn("水位信息查询异常", stcd, b);
			return;
		}
		let d = {
			"jsonrpc": "2.0",
			"method": "waterRealTime",
			"id": 0,
			"params": {
				"waterInfoVo": {
					"stcd": (stcd || 2109) + ""
				}
			}
		}
		console.log("查询测站实时水位信息", d);
		this.hGdian(`${this._v1Root}/water/waterInfo`, d, r => b?.(r.data?.[0]));
	}


	/**监控接口2
	 * @param {Object} rt
	 * @param {Object} d
	 * @param {Object} b
	 */
	hServerCam(rt, d, b) {
		//摄像头查询视频预览流
		let p = window.audioHost + "/api/Agency/GetDat";
		let dat = this.parmApi(p, d);
		//	console.log("广播数据",dat);
		this.hGetDatApi3(dat, (t) => {
			//console.log("水位信息查询：", t, d);
			let r = null;
			try {
				if (typeof (t) === 'object') {
					r = t;
				} else {
					r = t; //eval('(' + t + ')'); //
				};
				b?.(r.result || r);
			} catch (e) {
				console.error("异常转换：", t, e);
			}
		});
	}


	//监控分组
	hServerCamGroup(b) {
		let d = {
			"jsonrpc": "2.0",
			"method": "queryCamGroups",
			"id": 65155,
			"params": {
				"groupId": 1,
				"userName": this.userNameNH // "system"
			}
		};

		this.hServerCam("", d, r => {
			let group = r.group?.childs[0]?.childs;
			console.log("监控分组", r);
			b?.(group || r);
		});
	}

	//监控列表
	hServerCams(b) {
		// "userName": "system",
		// "id": 8 //摄像头id，三选一
		// "ids": [1, 3] //摄像头id，三选一
		// "condition": {} //多条件查询，三选一，具体格式在下面

		let d = {
			"jsonrpc": "2.0",
			"method": "queryCams",
			"id": 65155,
			"params": {
				"userName": this.userNameNH, // "system",
				"condition": {
					"offset": 0,
					"limit": 100,
					"groupId": 1, //传入分组ID
					"state": -1,
					"pullStreamMode": -1,
					"defaultStreamType": -1,
					"manufacturer": -1,
					"deviceType": -1,
					"ebrId": "",
					"name": "",
					"ip": "",
					"groupName": ""
				}
			}
		};
		//console.log("请求监控列表：", d);
		this.hServerCam("", d, r => {
			b?.(r.cameras || r);
		});
	}

	hGetCamUrl(u) {
		return u.replace("http://172.23.200.10:55580", "https://210.83.70.93:8443/camera_hls_proxy");
	}
	hGetCamUrlWss(u) {
		return u.replace("ws://172.23.200.10:55580", "wss://210.83.70.93:8443/camera_hls_proxy");
	}

	//监控播放
	hServerCamPlay(codes, b) {
		// if (!codes || codes.length < 1) {
		// 	return;
		// }
		// let codeStr = JSON.stringify(codes);
		// let codeStr = JSON.stringify(codes);
		//		console.log("查询流", codeStr);
		// let cs = [];
		// for (var i = 0; i < codes.length; i++) {
		// 	cs.push({
		// 		//"id": 1, //摄像头ID
		// 		"identifierId": codes[i], //和id二选一就行
		// 		"streamType": 2 //1 //指定码流--主码流/子码流/第三码流，如果指定不存在，则自动获取后台默认指定的码流 
		// 	});
		// };
		//  "parameter": "{\"cameraIndexCode\": \"5696bbaa163044c7bfb66465e168c09c\",\"streamType\": 0,\"protocol\": \"ws\",\"transmode\": 1,\"expand\": \"transcode=0\",\"streamform\": \"ps\"}"
		// let d = {
		// 	"jsonrpc": "2.0",
		// 	"method": "playVideos",
		// 	"id": 65155,
		// 	"params": {
		// 		"cams": cs
		// 	}
		// };
		let d = {
			"pathId": 176,
			"parameter": JSON.stringify({
				cameraIndexCode: codes,
				streamType: 1,
				protocol: "ws",
				transmode: 1,
				expand: "transcode=0",
				streamform: "ps"
			})
		};

		this.hServerCam("", d, r => {
			if (r) {
				//console.log("播放", r.cams);
				let urls = r
				// let urls = r.cams.map(t => this.hGetCamUrlWss(t.workers?.[0]?.wsFlvUrl));
				//r.cams.map(t => this.hGetCamUrl(t.workers?.[0]?.hlsUrl));
				b?.(urls);
			} else {
				hMsgWarn(r?.errMsgs?.[0]?.msg + codes);
			}
		});
	}


	//监控云台控制
	hServerPtz(code, act, cmd, b) {

		//"identifierId":"摄像头唯一值",//和id二选一
		//"id":1,//摄像头id" 和identifierId二选一
		//"presetIndex":1,//预置点编码,可选项 1-300，默认值为1，当没有这个节点时，后台默认1
		let d = {
			"jsonrpc": "2.0",
			"method": "cameraPtzControll",
			"id": 65155,
			"params": {
				"userName": this.userNameNH, //"system",
				"id": code,
				"action": act, //动作0：开始 1：停止
				"command": cmd, //0:左转 1:右转 2:上转 3:下转 4:左上 5:左下 6:右上 7:右下 8:焦距变大 9:焦距变小 10:焦点前移 11:焦点后移 12:光圈扩大 13:光圈缩小 14:接通雨刷开关 15:开始记录轨迹 16:停止记录轨迹 17:开始轨迹 18:停止轨迹 19:到预置点
				//当摄像头为海康isc安防平台，且command =  19（到预置点时）
				"speed": 50, //速度，可选项 1-100，默认值为50，当没有这个节点时，后台默认50
			}
		};
		this.hServerCam("", d, r => {
			console.log("监控云台：", d, r);
			b?.(r.result || r);
		});
	}
	hServerBroadcast__XXX(b) {

		let d = {
			"jsonrpc": "2.0",
			"method": "queryAdapterTaskInfo",
			"id": 11752,
			"params": {
				"ebmId": "43302260000000314010201202304200125" //指定任务
			}
		};
		this.hGdianResource(d, b);
		/**
		 * 返回数据 
		 */
	}
}